package org.xxpay.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.entity.AppNotify;
import org.xxpay.core.entity.AppNotifyExample;
import org.xxpay.core.service.IAppNotifyService;
import org.xxpay.service.dao.mapper.AppNotifyMapper;

import java.util.Date;
import java.util.List;


@Service
public class AppNotifyServiceImpl implements IAppNotifyService {

    @Autowired
    AppNotifyMapper appNotifyMapper;

    @Override
    public int add(AppNotify appNotify) {
        return appNotifyMapper.insertSelective(appNotify);
    }

    @Override
    public int update(AppNotify appNotify) {
        return appNotifyMapper.updateByPrimaryKeySelective(appNotify);
    }

    @Override
    public AppNotify find(AppNotify appNotify) {
        return appNotifyMapper.selectByPrimaryKey(appNotify.getId());
    }

    @Override
    public List<AppNotify> select(int offset, int limit, AppNotify appNotify, Date createTimeStart, Date createTimeEnd) {
        AppNotifyExample example = new AppNotifyExample();
        example.setOrderByClause("createTime desc");
        example.setOffset(offset);
        example.setLimit(limit);
        AppNotifyExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, appNotify, createTimeStart, createTimeEnd);
        return appNotifyMapper.selectByExample(example);
    }

    @Override
    public Integer count(AppNotify appNotify, Date createTimeStart, Date createTimeEnd) {
        AppNotifyExample example = new AppNotifyExample();
        AppNotifyExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, appNotify, createTimeStart, createTimeEnd);
        return appNotifyMapper.countByExample(example);
    }

    @Override
    public Boolean deleteByIds(List<Long> appIds) {
        for (Long appId:appIds) {
            int i = appNotifyMapper.deleteByPrimaryKey(appId);
            if (i != 1){
                return false;
            }
        }
        return true;
    }

    void setCriteria(AppNotifyExample.Criteria criteria, AppNotify appNotify, Date createTimeStart, Date createTimeEnd) {
        if(appNotify != null) {
            if(StringUtils.isNotEmpty(appNotify.getChannelType())) criteria.andChannelTypeEqualTo(appNotify.getChannelType());
            if(appNotify.getAmount() != null && appNotify.getAmount() != 0) criteria.andAmountEqualTo(appNotify.getAmount());
            if(appNotify.getStatus() != null && appNotify.getStatus().byteValue() != -99) criteria.andStatusEqualTo(appNotify.getStatus());
        }
        if(createTimeStart != null) {
            criteria.andCreateTimeGreaterThanOrEqualTo(createTimeStart);
        }
        if(createTimeEnd != null) {
            criteria.andCreateTimeLessThanOrEqualTo(createTimeEnd);
        }
    }
}
